/**
 * properties 文件读取工具
 * 
 * @author lms 2016.03.31
 * @author lms update 2021.03.28 增加保存接口
*/
package ms.core.tool;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;

public class PropTool{
	//private declarations
	String fileName = "";
	Properties prop=null;
	public Properties getProperties(){ return this.prop; }

	public static PropTool getInstance(String fileName) {
		return new PropTool(fileName);
	}

	/**
	 * constructor function
	 * @param fileName: fileName of configuration file
	 */
	public PropTool(String fileName){
		try {
			this.fileName = fileName;
			prop = new Properties();
			InputStream in = StreamTool.loadFileToStream(PropTool.class, fileName);
			prop.load(new InputStreamReader(in, "UTF-8"));
			in.close();
		}
		catch(Exception e){
			Log4j2Tool.error(PropTool.class, "PropTool读取"+fileName+"异常", e);
		}
	}

	//get property value
	public String getValue(String key, String defaultValue){
		if (prop==null)
			return defaultValue;

		String tmp = prop.getProperty(key);
		if (StrTool.isBlank(tmp))
			return defaultValue;

		return tmp;
	}

	//set property value
	public void setValue(String key, String value){
		if (prop==null) return;

		prop.setProperty(key, value);
	}
	
	/**
	 * 保存properties文件
	 * @return
	 */
	public boolean save() {
		try {
			OutputStream os = StreamTool.getOutputStream(fileName);
			prop.store(os, "");
			os.close();
			return true;
		} catch (Exception e) {
			Log4j2Tool.error(PropTool.class, "save:", e);
			return false;
		}
	}

	public static void main(String[] args) {
		PropTool tool = PropTool.getInstance("/config/system.properties");
		System.out.println(tool.getValue("pageSize", null));
	}
}
